/*
 * @Date: 2022-04-18 23:23:08
 * @LastEditors: Wangjun
 * @LastEditTime: 2022-04-18 23:36:04
 * @FilePath: \godriver\opdb\opsql\op.go
 * @Description:
 */
package opsql

import (
	"errors"
	"fmt"

	"gitee.com/haodreams/godriver/opdb"

	"gorm.io/gorm"
)

func ReadRealtimeData(op *gorm.DB, ids []interface{}) (rows []*opdb.Real, err error) {
	//m.ids 在根据点名获取id时自动赋值
	if len(ids) == 0 {
		return
	}

	defer func() {
		if e := recover(); e != nil {
			err = errors.New(fmt.Sprint(e))
		}
	}()

	db, err := op.DB()
	if err != nil {
		return
	}
	records, err := db.Query("Read Realtime", ids...)
	if err != nil {
		return
	}

	defer records.Close()
	if records.Next() {
		err = op.ScanRows(records, &rows)
		if err != nil {
			return
		}
	}
	return
}

func WriteRealtimeData(op *gorm.DB, list []interface{}) (err error) {
	db, err := op.DB()
	if err != nil {
		return
	}
	_, err = db.Exec("Write Realtime", list...)

	return
}

func InsertPoints(op *gorm.DB, points []*opdb.Point) (err error) {
	//err := real.GetEngine().Exec("WRITE Point", needInsert...).Error
	if len(points) == 0 {
		return
	}
	needInsert := make([]interface{}, len(points))
	for i := range points {
		needInsert[i] = points[i]
	}
	db, err := op.DB()
	if err != nil {
		return
	}

	_, err = db.Exec("WRITE Point", needInsert...)

	return
}
